<template>
  <el-dialog v-model="show" title="内容选择" draggable width="1200px" align-center>
    <div class="dialog-header">
      <div class="search-section">
        <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData.params"
          @onSubmit="handleSearch" />
        <el-button v-if="orderFields.length" type="primary" plain @click="showSortDialog = true">结果排序</el-button>
      </div>
      <div class="create-section">
        <el-button type="primary" plain @click="handleCreate">内容不够？去创作</el-button>
      </div>
    </div>

    <!-- 排序设置弹窗 -->
    <el-dialog v-model="showSortDialog" title="排序设置" width="500px" append-to-body>
      <div class="sort-tip" style="margin-bottom: 12px; color: #909399; font-size: 13px;">
        搜索结果将按照下方设置的排序规则返回。<br />可拖动左侧图标调整排序优先级，越靠前优先级越高。
      </div>
      <draggable v-model="sortFields" item-key="field" handle=".drag-handle" class="sort-list">
        <template #item="{ element, index }">
          <div class="sort-item">
            <div class="field-info">
              <i class="iconfont drag-handle">&#xe7dc;</i>
              <span class="index">{{ index + 1 }}.</span>
              <span class="name">{{ element.name }}</span>
            </div>
            <div class="sort-controls">
              <el-switch v-model="element.isOpen" size="small" />
              <el-radio-group v-model="element.sortType" size="small" :disabled="!element.isOpen">
                <el-radio-button label="asc">降序</el-radio-button>
                <el-radio-button label="desc">升序</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </template>
      </draggable>
      <template #footer>
        <el-button @click="showSortDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSortConfirm">确定</el-button>
      </template>
    </el-dialog>

    <div class="table-list">
      <RuifoxTable :loading="tableLoading" v-model:tableData="tableData" v-model:fieldList="fieldList" :key="model.id + 'table'"
        :default-index="true" :default-checkbox="true" :tableProps="tableProps" @handleSearch="handleSearch">
        <!-- 多选 -->
        <template #default-checkbox="{ element }">
          <div class="table-div-check">
            <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" size="" />
          </div>
        </template>
        <template #options="{ element }">
          <div class="table-td-option unmover">
            <el-button type="primary" link @click="handleDetail(element)">详情</el-button>
          </div>
        </template>
        <!-- 标题缩略图 -->
        <template #thumb="{ element }">
          <div class="table-td-title">
            <div class="title-box">
              <el-popover>
                <template #reference>
                  <div class="thumb-box" style="max-width: 42px;height: 24px;" v-show="element.thumb">
                    <img :src="element.thumb" alt="" style="max-width: 100%;max-height: 100%">
                  </div>
                </template>
                <template #default>
                  <div class="thumb-box" style="max-width: 150px;max-height: 300px">
                    <img :src="element.thumb" alt="" style="width: 100%;height: 100%">
                  </div>
                </template>
              </el-popover>
            </div>
          </div>
        </template>
        <template #publish_info="{ element }">
          <div class="table-td-publish-state">
            {{ getPublishText(element) }}
          </div>
        </template>
      </RuifoxTable>
    </div>
    <PaginationView :total="queryData.total" :pageSize="queryData.pageSize" :currentPage="queryData.currentPage"
      :allChoose="isAllChooseBtn" :pageChoose="isPageChooseBtn" :checkedNum="checkedNum" @changeSize="handleSizeChange"
      @currentChange="handleCurrentChange" @changePageChoose="handlePageChoose" @changeAllChoose="handleAllChoose"
      @cancelChoose="handleResetPagination" @invertChoose="handleInvertChoose" @refreshList="getTableData" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="showTimeDialog = true" :disabled="!checkedList.length">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 时间选择弹窗 -->
  <el-dialog v-model="showTimeDialog" title="设置发布时间" width="300px" append-to-body>
    <div class="time-form">
      <el-form :model="timeForm" label-width="auto" label-position="right">
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="timeForm.publish_time"
            type="datetime"
            placeholder="选择发布时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="x"
            @change="handlePublishTimeChange"
          />
        </el-form-item>
        <el-form-item label="撤稿时间">
          <el-date-picker
            v-model="timeForm.withdraw_time"
            type="datetime"
            placeholder="选择撤稿时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="x"
            :disabled-date="disabledWithdrawDate"
            :disabled-time="disabledWithdrawTime"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="showTimeDialog = false">取消</el-button>
      <el-button type="primary" @click="handlePublish">确定</el-button>
    </template>
  </el-dialog>

  <!-- 内容详情预览 -->
  <el-dialog v-model="previewDialog" title="详情" width="1210px">
    <ResourcePreview v-if="previewDialog" :curShare="previewData" />
  </el-dialog>
</template>

<script setup>
/* eslint-disable */
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { selectUserResourcePage, publishContent } from '@/api/notice'
import { tableList as mixTable, jumpRoute } from '@ruifox-cms/utils'
import { ResourcePreview } from '@ruifox-cms/components'
import draggable from 'vuedraggable'
import { ElMessage } from 'element-plus'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  model: {
    type: Object,
    default: () => {}
  },
  searchCmpArray: {
    type: Array,
    default: () => []
  },
  fieldList: {
    type: Array,
    default: () => []
  },
  orderFields: {
    type: Array,
    default: () => []
  },
  // catIds: {
  //   type: Array,
  //   default: () => []
  // }
})
const emits = defineEmits(['update:show', 'success'])

const show = computed({
  get: () => props.show,
  set: (value) => emits('update:show', value)
})
// 表头数据(排除掉站点特有的字段)
const fieldList = ref([])
const getFieldList = () => {
  fieldList.value = props.fieldList.filter(item => item.id)
  fieldList.value.push({ name: '引用情况', field: 'publish_info' },)
  fieldList.value.push({ name: '操作', field: 'options', width: 60 })
}
getFieldList()

const getPublishText = (data) => {
  if (data.publish_info.length === 0) {
    return '未引用'
  }
  if (data.publish_info.length === 1) {
    return `${data.publish_info[0].categoryName}已引用`
  }
  let columnName = data.publish_info.slice(0, 2).map(item => item.categoryName).join('、')
  return `${columnName}等${data.publish_info.length}个栏目已引用`
}

const tableProps = ref({
  labelKey: 'name',
  valueKey: 'field'
})

const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllSearch,
  isAllChooseBtn,
  isPageChooseBtn,
  checkedList,
  getTableData,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination
} = mixTable({
  getListApi: selectUserResourcePage
})

// 初始化查询数据
Object.assign(queryData, {
  currentPage: 1,
  pageSize: 10,
  modelId: props.model.id,
  params: {},
  orderFields: [],
  orderTypeMap: {}
})
// 排序相关
const showSortDialog = ref(false)
const sortFields = ref([])
const getSortFields = () => {
  sortFields.value = props.orderFields.map(item => ({
    ...item,
    isOpen: false,
    sortType: 'asc'
  }))
}
getSortFields()

// 修改搜索处理函数，加入排序参数
const handleSearch = (params = {}) => {
  // 更新搜索参数
  Object.assign(queryData.params, params)

  // 更新排序参数
  const activeSortFields = sortFields.value.filter(item => item.isOpen)
  queryData.orderFields = activeSortFields.map(item => item.field)
  queryData.orderTypeMap = {}
  activeSortFields.forEach(item => {
    queryData.orderTypeMap[item.field] = item.sortType
  })

  getTableData(queryData)
}

// 确认排序设置
const handleSortConfirm = () => {
  showSortDialog.value = false
  handleSearch()
}

// 时间选择相关
const showTimeDialog = ref(false)
const timeForm = ref({
  publish_time: '',
  withdraw_time: ''
})

// 发布内容
const handlePublish = async () => {
  if (!timeForm.value.publish_time) {
    ElMessage.warning('请选择发布时间')
    return
  }

  const dataInfos = {}
  checkedList.value.forEach(id => {
    dataInfos[id] = {
      publish_time: timeForm.value.publish_time,
      withdraw_time: timeForm.value.withdraw_time
    }
  })

  const params = {
    dataInfos,
    isAllChoose: isAllSearch.value,
    modelId: props.model.id,
    // catIds: props.catIds,
    orderFields: queryData.orderFields,
    orderTypeMap: queryData.orderTypeMap,
    params: queryData.params
  }
  try {
    const res = await publishContent(params)
    if (res.code === 20000) {
      ElMessage.success('发布成功')
      showTimeDialog.value = false
      show.value = false
      emits('success')
    }
  } catch (error) {
    console.error('发布失败:', error)
  }
}

const handleCreate = () => {
  jumpRoute('/resource/manage/setting', { modelId: props.model.id, publishType: props.model.publishType, folderId: 0 }, '_blank')
}

// 处理发布时间变化
const handlePublishTimeChange = (val) => {
  // 如果撤稿时间小于发布时间，清空撤稿时间
  if (timeForm.value.withdraw_time && timeForm.value.withdraw_time < val) {
    timeForm.value.withdraw_time = ''
  }
}

// 禁用撤稿日期
const disabledWithdrawDate = (time) => {
  if (!timeForm.value.publish_time) return false
  const publishDate = new Date(Number(timeForm.value.publish_time))
  return time.getTime() < publishDate.setHours(0, 0, 0, 0)
}

// 禁用撤稿时间
const disabledWithdrawTime = (date) => {
  if (!timeForm.value.publish_time) return false
  const publishTime = Number(timeForm.value.publish_time)
  const currentTime = date.getTime()
  
  // 如果是同一天，禁用小于发布时间的时间
  if (new Date(publishTime).toDateString() === date.toDateString()) {
    return {
      disabledHours: () => {
        const publishHour = new Date(publishTime).getHours()
        return Array.from({ length: publishHour }, (_, i) => i)
      },
      disabledMinutes: (hour) => {
        if (hour === new Date(publishTime).getHours()) {
          const publishMinute = new Date(publishTime).getMinutes()
          return Array.from({ length: publishMinute }, (_, i) => i)
        }
        return []
      },
      disabledSeconds: (hour, minute) => {
        if (hour === new Date(publishTime).getHours() && 
            minute === new Date(publishTime).getMinutes()) {
          const publishSecond = new Date(publishTime).getSeconds()
          return Array.from({ length: publishSecond }, (_, i) => i)
        }
        return []
      }
    }
  }
  return {}
}

// 详情查看
const previewDialog = ref(false)
const previewData = ref({})
const handleDetail = (data) => {
  previewData.value = {
    modelId: props.model.id,
    resourceData: data
  }
  previewDialog.value = true
}

onMounted(() => {
  getTableData()
  window['updatePage'] = () => {
    ElMessage.success('检测到内容更新，已刷新列表')
    getTableData()
  }
})

onBeforeUnmount(() => {
  window['updatePage'] = null
})
</script>

<style lang='scss' scoped>
.dialog-header {
  position: relative;
  margin-bottom: 16px;

  .search-section {
    display: flex;
    align-items: flex-start;
    gap: 16px;
  }

  .create-section {
    position: absolute;
    right: 0;
    top: 0;
  }

  .el-button {
    .iconfont {
      margin-right: 4px;
    }
  }
}

.sort-list {
  .sort-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #EBEEF5;

    &:last-child {
      border-bottom: none;
    }

    .field-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .drag-handle {
        cursor: move;
        color: $mainColor;
      }

      .index {
        width: 24px;
        color: #909399;
      }

      .name {
        color: #606266;
      }
    }

    .sort-controls {
      display: flex;
      align-items: center;
      gap: 16px;
    }
  }
}

.table-list {
  .table-td-title {
    display: flex;
    align-items: center;

    .title-tips {
      .iconfont {
        font-size: 14px;
        color: $mainColor;
        margin-right: 3px;
      }

      span {
        color: #aaa;
        margin-right: 20px;
        position: relative;
      }

      span+span:before {
        content: '|';
        position: absolute;
        left: -10px;
        top: -8px;
      }
    }

    .title-box {
      display: flex;
      justify-content: center;
      align-items: center;

      p {
        @include textEllipsis(16px, 1)
      }

      .iconimg {
        display: inline-block;
        width: 16px;
        margin-right: 5px;

        i {
          color: #2CBF77;
          font-size: 15px;
        }
      }

      .a-icon {
        display: inline-block;
        width: 16px;
        background-color: $mainColor;
        color: $white;
        line-height: 16px;
        text-align: center;

        i {
          font-size: 14px;
        }
      }

      .p-icon {
        display: flex;
        align-items: center;
        width: 20px;
        color: #2CBF77;

        i {
          font-size: 18px;
        }
      }

      .thumb-box {
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>